package com.hongyun.tms.serializer;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> implements ContextualSerializer {

    private String pattern = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (null != value) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            gen.writeString(formatter.format(value));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        AnnotationMap annotated = property.getMember().getAllAnnotations();
        JsonFormat jsonFormat = annotated.get(JsonFormat.class);
        if (jsonFormat != null && jsonFormat.pattern() != null) {
            // 为 JsonFormat 创建一个单独的序列化器
            LocalDateTimeSerializer datetimeSerializer = new LocalDateTimeSerializer();
            datetimeSerializer.pattern = jsonFormat.pattern();
            return datetimeSerializer;
        }
        return this;
    }
}